<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * SimplyPost
 *
 * @author		Pascal Kriete
 * @package		SimplyPost
 * @copyright	Copyright (c) 2008, Pascal Kriete
 * @license 	http://www.gnu.org/licenses/lgpl.txt
 */

// ------------------------------------------------------------------------

/**
 * Login Controller
 *
 * @package		SimplyPost
 * @subpackage	Member
 * @category	Controller
 * @author		Pascal Kriete
 */

class Login extends BaseController {
	
	/**
	 * Controller
	 *
	 * @access	public
	 */
	function Login()
	{
		parent::BaseController();
		$this->lang->load('member');
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Show and validate login form
	 *
	 * @access	public
	 */
	function index()
	{
		set_title($this->lang->line('member_login_title'));
		$this->breadcrumb->from_path();
		
		$this->load->helper('form');
		
		$this->load->library('validation');
		
		$rules['email'] = "trim|required|xss_clean";
		$rules['password'] = "trim|required";
		$rules['submit'] = "callback__verify";
		$this->validation->set_rules($rules);
		
		$fields['email'] = $this->lang->line('login_email');
		$fields['password'] = $this->lang->line('login_password');
		$fields['submit'] = 'Credentials';
		$this->validation->set_fields($fields);
		
		$this->validation->set_message('required', $this->lang->line('login_field_required'));
		$this->validation->set_error_delimiters('<p style="color:#900">', '</p>');

		if ($this->validation->run() == FALSE)
		{
			$this->load->view('login');
		}
		else
		{
			redirect('home');
		}
	}
	
	// ------------------------------------------------------------------------
	
	/**
	 * Login Validation Callback
	 *
	 * @access	private
	 * @param	string
	 * @return	bool
	 */
	function _verify($data)
	{
		$this->load->library('auth');
		
		$email = $this->input->post('email');
		$password = $this->input->post('password');
		$db_pass = secure_password($email, $password);
		
		$ans = $this->plugin->process_login();
		
		if ($ans[0] === FALSE) {
			$this->validation->set_message('_verify', $ans[1]);
			return FALSE;
		}
		
		$credentials = array('email' => $email, 'password' => $db_pass);
		if($this->auth->try_login($credentials) === TRUE)
		{
			return TRUE;
		}
		else
		{
			$this->validation->set_message('_verify', $this->lang->line('login_cred_missmatch'));
			return FALSE;
		}
	}
}